#include "protocol.h"

// 发送带长度和分隔符的消息
void sendMessage(int fd, const std::string& message) 
{
    uint32_t length = message.size(); // 获取消息正文长度
    uint32_t net_length = htonl(length); // 转换为网络字节序
    char delimiter = '\3'; // 分隔符

    // 创建完整的数据包：长度 + 分隔符 + 正文
    char buffer[sizeof(net_length) + sizeof(delimiter) + length];
    memcpy(buffer, &net_length, sizeof(net_length));
    memcpy(buffer + sizeof(net_length), &delimiter, sizeof(delimiter));
    memcpy(buffer + sizeof(net_length) + sizeof(delimiter), message.c_str(), length);

    if (send(fd, buffer, sizeof(buffer), 0) == -1) 
    {
        std::cerr << "Failed to send message" << std::endl;
    }
}

// 接收带长度和分隔符的消息
string receiveMessage(int fd) 
{
    char buffer[sizeof(uint32_t) + sizeof(char) + BUFFER_SIZE];
    ssize_t received = recv(fd, buffer, sizeof(buffer), 0);
    if (received <= 0) 
    {
        std::cerr << "Failed to receive message or connection closed" << std::endl;
        return "";
    }

    // 解析长度字段
    uint32_t length;
    memcpy(&length, buffer, sizeof(length));
    length = ntohl(length); // 转换为主机字节序

    // 验证分隔符
    char delimiter;
    memcpy(&delimiter, buffer + sizeof(length), sizeof(delimiter));
    if (delimiter != '\3') 
    {
        std::cerr << "Invalid delimiter received" << std::endl;
        return "";
    }

    // 提取正文内容
    std::string message(buffer + sizeof(length) + sizeof(delimiter), length);
    return message;
}